package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

// 查询今日佳人
@DubboService
public class RecommendUserServiceImpl implements RecommendUserService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findTodayBest(Long toUserId) {
        // 1.构建条件
        Query query = new Query(Criteria.where("toUserId").is(toUserId)
        ).with(Sort.by(Sort.Order.desc("score")))
                .skip(0).limit(1);

        // 2.查询推荐用户
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        // 3.返回一条
        return recommendUser;
    }


    // 查询推荐用户列表
    @Override
    public PageBeanVo findByPage(Long toUserId, Integer pageNum, Integer pageSize) {
        //1.创建条件对象(用户id)
        Query query = new Query(Criteria.where("toUserId").is(toUserId));

        //2.查询推荐用户表获取总条数
        long count = mongoTemplate.count(query, RecommendUser.class);

        //3.给条件对象追加参数(分页和排序)
        query.with(Sort.by(Sort.Order.desc("score")))
                .skip((pageNum - 1) * pageSize + 1).limit(pageSize);

        //4.查询当前页的数据集合
        List<RecommendUser> list = mongoTemplate.find(query, RecommendUser.class);

        /*
        推荐的用户只有1个
        总记录数就是1,但是查询list大小为0
        最好封装pageBeanVo的时候,对count进行重新计算
         */

        if (CollUtil.isNotEmpty(list) && list.size() == 0) {
            count = 0;
        } else if (list.size() > 1) {
            count = count - 1;
        }

        //5.封装pageBeanVo且返回
        return new PageBeanVo(pageNum, pageSize, count, list);
    }

    // 查询推荐的用户详情
    @Override
    public RecommendUser findPersonalInfo(Long toUserId, Long jiaRenId) {
        //1.创建条件对象(俩id)
        Query query = new Query(Criteria.where("toUserId").is(toUserId)
                .and("userId").is(jiaRenId));
        //2.查询推荐表获取数据,返回推荐用户
        return mongoTemplate.findOne(query, RecommendUser.class);
    }
}
